<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Response;

/**
 * 
 *
 * @icon fa fa-qrcode
 */
class Qrcode extends Backend
{

    /**
     * Qrcode模型对象
     * @var \app\admin\model\Qrcode
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Qrcode;

    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['extend','store'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                
                $row->getRelation('extend')->visible(['name','mobile']);
				$row->getRelation('store')->visible(['name']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    public function export()
    {

        if ($this->request->isPost()) {
            set_time_limit(0);
            $search = $this->request->post('search');
            $ids = $this->request->post('ids');
            $filter = $this->request->post('filter');
            $op = $this->request->post('op');
            $columns = $this->request->post('columns');

            $this->relationSearch = true;
            $whereIds = $ids == 'all' ? '1=1' : ['qrcode.id' => ['in', explode(',', $ids)]];
            $this->request->get(['search' => $search, 'ids' => $ids, 'filter' => $filter, 'op' => $op]);

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['user','store'])
                ->where($whereIds)
                ->where($where)
                ->order($sort, $order)
                ->select();

            $arr = [];
            foreach ($list as $k=>$v){
                $arr[$k] = ROOT_PATH."public". $v['image'];
            }

            $path = ROOT_PATH."public/uploads/qrcode/download.zip";
            $result = $this->create_zip($arr,$path,true);

            $file = $path;
            if(file_exists($file)){
                header("Content-type:application/octet-stream");
                $filename = basename($file);
                header("Content-Disposition:attachment;filename = ".$filename);
                header("Accept-ranges:bytes");
                header("Accept-length:".filesize($file));
                readfile($file);
            }else{
                echo "<script>alert('文件不存在')</script>";
            }
        }



    }

    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        $last = $this->model->order('id desc')->find();
        $last['id'] = $last['id'] ?? 1;
//        dump($last['id']);
//        halt($params['num'] + $last['id']);
        for ($i = $last['id'];$i<$params['num']+$last['id'];$i++){
            $img = $this->qrCode(request()->domain().'/#/?type=blind_store&blind_id='.$i);
            $this->model->create(['image'=>$img]);
        }

        $this->success('生成成功');
    }



    public function qrCode($text = ''){
        //生成二维码 传生成二维码的文本内容
        $qrCode    = $this->build($text);
        $qrCodeUrl =  '/uploads/qrcode/'.$qrCode;
        return $qrCodeUrl;
    }

    public function serverUrl(){
        $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
        return  $http_type . $_SERVER['HTTP_HOST'];
    }

// 生成二维码
    public function build($text = ''){
        $config = get_addon_config('qrcode');
        $params = $this->request->get();
        $params = array_intersect_key($params, array_flip(['text', 'size', 'padding', 'errorlevel', 'foreground', 'background', 'logo', 'logosize', 'logopath', 'label', 'labelfontsize', 'labelalignment']));

        $params['text'] = $text??$config['text'];
        $params['label'] = $this->request->get('label', $config['label'], 'trim');
        $qrCode = \addons\qrcode\library\Service::qrcode($params);
        $mimetype = $config['format'] == 'png' ? 'image/png' : 'image/svg+xml';

        $response = Response::create()->header("Content-Type", $mimetype);

        // 直接显示二维码
        header('Content-Type: ' . $qrCode->getContentType());
        $response->content($qrCode->writeString());

        // 写入到文件
        if ($config['writefile']) {
            $qrcodePath = ROOT_PATH . 'public/uploads/qrcode/';
            if (!is_dir($qrcodePath)) {
                @mkdir($qrcodePath);
            }
            if (is_really_writable($qrcodePath)) {
                $filePath = $qrcodePath . md5(implode('', $params)) . '.' . $config['format'];
                $qrCode->writeFile($filePath);
                $code_name = md5(implode('', $params)) . '.' . $config['format'];
            }
        }

        return $code_name;
    }

    //要压缩的文件(数组)   保存的文件目录(均为绝对路径)   是否强制覆盖
    public function create_zip($files = array(),$destination = '',$overwrite = false) {
        //如果zip文件已经存在并且设置为不重写返回false
        if(file_exists($destination)) {
            unlink($destination);
        }else{
            $overwrite=false;
        }
        $valid_files = array();
        //获取到真实有效的文件名
        if(is_array($files)) {
            foreach($files as $file) {
                if(file_exists($file)) {
                    $valid_files[] = $file;
                }
            }
        }

        //如果存在真实有效的文件
        if(count($valid_files)) {
            $zip = new \ZipArchive();
            //打开文件       如果文件已经存在则覆盖，如果没有则创建
            if($zip->open($destination,$overwrite ? \ZIPARCHIVE::OVERWRITE : \ZIPARCHIVE::CREATE) !== true) {
                return false;
            }
            //向压缩文件中添加文件
            foreach($valid_files as $file) {
                $zip->addFile($file,basename($file));  //第一个参数是去取得路劲  第二个参数是压缩文件里的名字
            }
            //关闭文件
            $zip->close();
            //check to make sure the file exists
            //检测文件是否存在
            return file_exists($destination);
        }else{
            //如果没有真实有效的文件返回false
            return false;
        }
    }



}
